package com.cee.admin.config.web;

import com.cee.admin.config.converter.DateConverter;
import com.cee.admin.config.converter.LocalDateConverter;
import com.cee.admin.config.converter.LocalDateTimeConverter;
import com.cee.admin.config.interceptor.FileCleanContextInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.format.FormatterRegistry;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;


/**
 * web mvc 的配置
 *
 * @author rxliuli
 */
@Configuration
public class CustomWebMvcConfigurer implements WebMvcConfigurer {

    @Bean
    public CustomCorsFilter myCorsFilter(CorsProperties corsProperties){
        CorsConfiguration config = new CorsConfiguration();
        config.setMaxAge(corsProperties.getAccessControlMaxAge());
        config.setAllowCredentials(corsProperties.getAccessControlAllowCredentials());
        config.setAllowedOriginPatterns(corsProperties.getAccessControlAllowOrigin());
        config.setAllowedHeaders(corsProperties.getAccessControlAllowHeaders());
        config.setAllowedMethods(corsProperties.getAccessControlAllowMethods());
        UrlBasedCorsConfigurationSource configSource = new UrlBasedCorsConfigurationSource();
        configSource.registerCorsConfiguration("/**", config);
        return new CustomCorsFilter(configSource);
    }

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        WebMvcConfigurer.super.addCorsMappings(registry);
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {

        registry.addInterceptor(new FileCleanContextInterceptor())
                .addPathPatterns("/api/**");
    }

    @Override
    public void addFormatters(FormatterRegistry formatterRegistry) {
        formatterRegistry.addConverter(new LocalDateConverter());
        formatterRegistry.addConverter(new LocalDateTimeConverter());
        formatterRegistry.addConverter(new DateConverter());
    }


}
